package org.zxl.iotest.netty.test1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class ServerInboundHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(ServerInboundHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("server channel active... ");
        ctx.fireChannelActive();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, "utf-8");
        String response = "ServerInboundHandler：" + body ;
        logger.info(response);
        System.out.println("1.read");
//        ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
        ByteBuf byteBuf = Unpooled.copiedBuffer(response.getBytes());
        // future完成后触发监听器, 此处是写完即关闭(短连接). 因此需要关闭连接时, 要通过server端关闭. 直接关闭用方法ctx[.channel()].close()
        //.addListener(ChannelFutureListener.CLOSE);
        if("hello".equals(body)){
            //跳过ServerInboundHandler2，直接出站
            ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
        }else{
            //进入下一个InboundHandler
            ReferenceCountUtil.release(msg); //释放msg
            ctx.fireChannelRead(byteBuf);
        }

        ctx.channel().eventLoop().execute(new Runnable() {
            @Override
            public void run() {
                logger.info("用户自定义任务1");
            }
        });
        ctx.channel().eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                logger.info("用户自定义定时任务1");
            }
        }, 10, TimeUnit.SECONDS);
    }

//    @Override
    public void channelReadComplete(ChannelHandlerContext ctx)
            throws Exception {
        logger.info("读完了");
        ctx.flush();
        ctx.fireChannelReadComplete();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable t)
            throws Exception {
        logger.error("server error:{}", t.getMessage());
        t.printStackTrace();
//        ctx.close();
        //跳过ServerInboundHandler2，直接出站
        ctx.writeAndFlush(Unpooled.copiedBuffer(t.getMessage().getBytes()));
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        logger.info("写完了");
    }
}
